package com.rfid.project.web;

import java.text.DateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.ProjectDelayApply;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectDelayApplyService;
import com.rfid.project.service.ProjectService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;
import com.rfid.project.util.StringUtil;

@Controller
public class ProjectDelayApplyController {

	private static final Logger logger = LoggerFactory
			.getLogger(ProjectDelayApplyController.class);

	@Autowired
	private ProjectDelayApplyService projectDelayApplyService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private PeopleService peopleService;

	@RequestMapping(value = "/projectDelayApplymgr")
	public String projectDelayApplymgr(
			HttpServletRequest request,
			HttpServletResponse response, 
			Model model,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId) {
		model.addAttribute("project", this.projectService.findOne(projectId));
		return "projectDelayApplymgr";
	}

	@RequestMapping(value = "/queryProjectDelayApply")
	public String queryProjectDelayApply(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "originalFinishDateBegin", defaultValue = "") Date originalFinishDateBegin,
			@RequestParam(value = "originalFinishDateEnd", defaultValue = "") Date originalFinishDateEnd,
			@RequestParam(value = "targetFinishDateBegin", defaultValue = "") Date targetFinishDateBegin,
			@RequestParam(value = "targetFinishDateEnd", defaultValue = "") Date targetFinishDateEnd,
			@RequestParam(value = "applyPersonId", defaultValue = "-1") Long applyPersonId,
			@RequestParam(value = "applyTimeBegin", defaultValue = "") Date applyTimeBegin,
			@RequestParam(value = "applyTimeEnd", defaultValue = "") Date applyTimeEnd,
			@RequestParam(value = "applyReason", defaultValue = "") String applyReason,
			@RequestParam(value = "checkPersonId", defaultValue = "-1") Long checkPersonId,
			@RequestParam(value = "checkTimeBegin", defaultValue = "") Date checkTimeBegin,
			@RequestParam(value = "checkTimeEnd", defaultValue = "") Date checkTimeEnd,
			@RequestParam(value = "checkComment", defaultValue = "") String checkComment,
			@RequestParam(value = "ratifyPersonId", defaultValue = "-1") Long ratifyPersonId,
			@RequestParam(value = "ratifyTimeBegin", defaultValue = "") Date ratifyTimeBegin,
			@RequestParam(value = "ratifyTimeEnd", defaultValue = "") Date ratifyTimeEnd,
			@RequestParam(value = "ratifyComment", defaultValue = "") String ratifyComment,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectDelayApply> projectDelayApplys = projectDelayApplyService
				.findAll(projectId, originalFinishDateBegin,
						originalFinishDateEnd, targetFinishDateBegin,
						targetFinishDateEnd, applyPersonId, applyTimeBegin,
						applyTimeEnd, applyReason, checkPersonId,
						checkTimeBegin, checkTimeEnd, checkComment,
						ratifyPersonId, ratifyTimeBegin, ratifyTimeEnd,
						ratifyComment, status, pageNumber, pageSize, sort,
						order);
		JSONObject object = new JSONObject();
		object.put("total", projectDelayApplys.getTotalElements());
		JSONArray models = new JSONArray();
		for (ProjectDelayApply item : projectDelayApplys) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);
			
			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	@RequestMapping(value = "/findProjectDelayApply")
	public String findProjectDelayApply(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		ProjectDelayApply projectDelayApply = projectDelayApplyService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(projectDelayApply, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}

	private void wrapData(ProjectDelayApply item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("status", ProcessStatus.processStatusName(item.getStatus()));
		mod.put("statusCode", item.getStatus());
		mod.put("projectId", item.getProject().getId());
		mod.put("projectName", item.getProject().getName());
		mod.put("originalFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getOriginalFinishDate()));
		mod.put("targetFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getTargetFinishDate()));
		mod.put("applyReason", item.getApplyReason());
		mod.put("applyTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getApplyTime()));
		mod.put("checkTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getCheckTime()));
		
		String checkContent = item.getCheckComment();
		mod.put("checkComment", checkContent == null?"":checkContent);
		mod.put("ratifyTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getRatifyTime()));
		mod.put("ratifyComment", StringUtil.getString(item.getRatifyComment()));

		mod.put("applyPersonId", item.getApplyPerson().getId());
		mod.put("applyPersonName", item.getApplyPerson().getName());

		People checkPerson = item.getCheckPerson();
		if (null == checkPerson) {
			mod.put("checkPersonId", -1);
			mod.put("checkPersonName", "");
		} else {
			mod.put("checkPersonId", checkPerson.getId());
			mod.put("checkPersonName", checkPerson.getName());
		}

		People ratifyPerson = item.getRatifyPerson();
		if (null == ratifyPerson) {
			mod.put("ratifyPersonId", -1);
			mod.put("ratifyPersonName", "");
		} else {
			mod.put("ratifyPersonId", ratifyPerson.getId());
			mod.put("ratifyPersonName", ratifyPerson.getName());
		}
	}

	@RequestMapping(value = "/getProjectDelayApply")
	public String getProjectDelayApply(HttpServletRequest request,
			HttpServletResponse response, 
			@RequestParam(value = "id", defaultValue = "-1") Long id,
            RedirectAttributes redirectAttributes) {
		ProjectDelayApply item = projectDelayApplyService.findOne(id);
		
		JSONObject mod = new JSONObject();
		wrapData(item, mod);
		
		PageJsonBean.printObject(response, mod);
		return null;
	}
	
	@RequestMapping(value = "/editProjectDelayApply", method = RequestMethod.POST)
	public String editProjectDelayApply(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectDelayApply projectDelayApply,
			Model model, RedirectAttributes redirectAttributes) {
		People applyPerson = projectDelayApply.getApplyPerson();
		if(null == applyPerson || null == applyPerson.getId()){
			projectDelayApply.setApplyPerson((People)request.getSession().getAttribute("currentUser"));
		}
		projectDelayApplyService.saveProjectDelayApply(projectDelayApply);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/checkProjectDelayApply", method = RequestMethod.POST)
	public String checkProjectDelayApply(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			@RequestParam(value = "checkComment", defaultValue = "") String checkComment,
			@Valid ProjectDelayApply projectDelayApply,
			Model model, RedirectAttributes redirectAttributes) {
		People currentUser = (People) request.getSession().getAttribute("currentUser");
		JSONObject result = new JSONObject();
		boolean flag = true;
		if (projectDelayApply != null && currentUser != null) {
			projectDelayApply.setCheckPerson(currentUser);
		}
		try {
			projectDelayApplyService.checkProjectDelayApply(projectDelayApply);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/ratifyProjectDelayApply", method = RequestMethod.POST)
	public String ratifyProjectDelayApply(
			HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectDelayApply projectDelayApply,
			Model model, RedirectAttributes redirectAttributes) {
		People currentUser = (People) request.getSession().getAttribute("currentUser");
		if (projectDelayApply != null && currentUser != null) {
			//修改项目完成申请信息
			People ratifyPerson = projectDelayApply.getRatifyPerson();
			if(null == ratifyPerson || null == ratifyPerson.getId()){
				projectDelayApply.setRatifyPerson(currentUser);
			}
		}
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			projectDelayApplyService.ratifyProjectDelayApply(projectDelayApply);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProjectDelayApply")
	public String delProjectDelayApply(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.projectDelayApplyService.deleteProjectDelayApply(id);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/revocationDelayApplyProjectDelayApply")
	public String revocationDelayApplyProjectDelayApply(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectDelayApply projectDelayApply,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectDelayApplyService.revocationDelayApplyProjectDelayApply(projectDelayApply);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

}
